﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.DXErrorProvider;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.Customization;
using DevExpress.XtraPivotGrid;
using DevExpress.XtraPrinting;
using DevExpress.XtraTab;
using DevExpress.XtraVerticalGrid;
using DevExpress.XtraVerticalGrid.Rows;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace DevTeam
{
    public partial class DevForm : DevExpress.XtraEditors.XtraForm
    {
        public bool isPopup = false;
        public List<BindingSource> sources;

        public static int WhoAmI { get { return Session.WhoAmI; } }

        public static int MyDept { get { return Session.CurrentUser.DepartmentId; } }

        public static bool AmI(params int[] UserIds) { return Session.CurrentUser.AmI(UserIds); }

        public bool isDeveloper { get { return Session.CurrentUser.isDeveloper; } }

        public bool isAdmin { get { return Session.CurrentUser.isAdmin; } }

        public List<CustomizationForm> CustomizationForms = new List<CustomizationForm>();

        public DevForm()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterParent;
        }

        public string HeaderText
        {
            set
            {
                txtInfo.Caption = value;

            }
        }

        public void ShowOnlyFooter()
        {
            MainToolbar.Visible = false;
        }
        private void DevForm_Load(object sender, EventArgs e)
        {
            InitValidation();

            this.Shown += DevForm_Shown;

            if (this.DesignMode)
                return;
        }

        void DevForm_Shown(object sender, EventArgs e)
        {
            MainToolbar.Visible = MainToolbar.VisibleLinks.Count > 1;

            /*
            if (DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName == "Office 2013")
                foreach (object b in MainToolbar.ItemLinks)
                    if (b is BarCheckItemLink)
                        ((BarCheckItemLink)b).Item.ItemAppearance.Pressed.ForeColor = Color.SteelBlue;
             */
        }

        public List<int> EnabledBarcodeTypes = new List<int>();
        public void EnableBarcodeType(params int[] Types)
        {
            foreach (int type in Types)
                EnabledBarcodeTypes.Add(type);
        }

        public delegate void BarcodeReadHandler(int Type, int Barcode);
        public event BarcodeReadHandler BarcodeRead;

        public void FireBarcodeRead(int Type, int Barcode)
        {
            if (BarcodeRead != null)
                this.BeginInvoke(new BarcodeReadHandler(BarcodeRead), new object[] { Type, Barcode });
        }

        public void AddVerticalGridGroup(VGridControl vgc, string Caption, BaseRow[] rows)
        {
            CategoryRow category = new CategoryRow(Caption);
            category.Name = Caption;
            category.Height = 20;
            category.Properties.ImageIndex = 0;

            vgc.Rows.Add(category);
            category.ChildRows.AddRange(rows);

            //(vgc.Rows[Caption] as CategoryRow)
            category.Appearance.Font = new System.Drawing.Font("Tahoma", 8, FontStyle.Bold);
            //category.Appearance.BackColor2 = Color.Gold;
        }

        public BaseRow AddVerticalGridItem(VGridControl vgc, string caption, string name, params RepositoryItem[] ri)
        {
            int RowHeight = 20;
            BaseRow row = vgc.Rows.GetRowByFieldName(name);
            if (row == null)
            {
                row = new EditorRow();
                row.Name = row.Properties.FieldName = name;
            }
            row.Properties.Caption = caption;
            row.Height = RowHeight;
            if (ri.Length > 0)
                row.Properties.RowEdit = ri[0];

            return row;
        }

        public BaseRow AddItem(VGridControl vgc, string name, Type t, params RepositoryItem[] ri)
        {
            BaseRow row = new EditorRow();
            row.Name =
                row.Properties.FieldName =
                row.Properties.Caption = name;
            row.Height = 20;
            if (ri.Length > 0)
            {
                ri[0].Name = name;
                row.Properties.RowEdit = ri[0];
            }
            else
                switch (t.ToString().ToLower())
                {
                    case "system.boolean":
                        row.Properties.RowEdit = new RepositoryItemCheckEdit();
                        row.Properties.UnboundType = DevExpress.Data.UnboundColumnType.Boolean;
                        break;

                    case "system.ınt32":
                    case "system.int32":
                        row.Properties.RowEdit = new RepositoryItemTextEdit();
                        row.Properties.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
                        break;

                    case "system.string":
                        row.Properties.RowEdit = new RepositoryItemTextEdit();
                        row.Properties.UnboundType = DevExpress.Data.UnboundColumnType.String;
                        break;

                    case "system.datetime":
                        row.Properties.RowEdit = new RepositoryItemDateEdit();
                        row.Properties.UnboundType = DevExpress.Data.UnboundColumnType.DateTime;
                        break;
                }

            return row;
        }

        public void MyAddField(GridView gv, string FieldName, ref int idx, params object[] ri)
        {
            GridColumn unb = gv.Columns.AddField(FieldName);
            unb.UnboundType = DevExpress.Data.UnboundColumnType.String;
            //unbColumn.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            //unbColumn.DisplayFormat.FormatString = "c";
            //unb.AppearanceCell.BackColor = Color.LemonChiffon;
            unb.OptionsColumn.AllowEdit = false;
            unb.VisibleIndex = ++idx;

            if (FieldName == "AksSeriId")
                unb.Caption = "SeriId";

            if (ri.Length > 0)
                unb.ColumnEdit = ri[0] as RepositoryItemGridLookUpEdit;

            unb.FilterMode = ColumnFilterMode.DisplayText;
            gv.Columns.Add(unb);
        }

        public PivotGridField AddNewField(PivotGridControl pgc, string FieldName, PivotArea pa)
        {
            PivotGridField fd = new PivotGridField();
            fd.FieldName = fd.Caption = FieldName;
            fd.CellFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            fd.CellFormat.FormatString = "#,###.##";
            pgc.Fields.Add(fd);
            fd.SetAreaPosition(pa, 0);

            fd.Name = "_" + FieldName;
            return fd;
        }

        public void pivotGrid_FieldValueDisplayText(object sender, PivotFieldDisplayTextEventArgs e)
        {
            //switch ((e.Field.FieldEdit).GetType().Name)
            if (e.Value != null && e.Field != null && e.Field.FieldEdit != null)
            {
                if (e.Field.FieldEdit is RepositoryItemGridLookUpEdit)
                    e.DisplayText = (e.Field.FieldEdit as RepositoryItemGridLookUpEdit).GetDisplayTextByKeyValue(e.Value).ToString();
                else if (e.Field.FieldEdit is RepositoryItemSearchLookUpEdit)
                    e.DisplayText = (e.Field.FieldEdit as RepositoryItemSearchLookUpEdit).GetDisplayTextByKeyValue(e.Value).ToString();
            }
        }

        public void ExportPivot(PivotGridControl pvg)
        {
            string FilePath = Dialogs.SaveFile("Excel Document", "Excel Documents|*.xlsx");

            XlsxExportOptions opt = new XlsxExportOptions();
            opt.TextExportMode = TextExportMode.Value;

            List<PivotGridField> totals = new List<PivotGridField>();

            foreach (PivotGridField f in pvg.Fields)
                if (f.Options.ShowTotals == true)
                {
                    f.Options.ShowTotals = false;
                    totals.Add(f);
                }

            pvg.ExportToXlsx(FilePath, opt);

            foreach (PivotGridField f in totals)
                f.Options.ShowTotals = true;

            FileManager.RunFile(FilePath);


        }

        #region Gridview Helpers
        string adet = "Adet: ";
        string toplam = "Toplam: ";
        public void gridview_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {

            GridView g = sender as GridView;
            DevExpress.XtraGrid.Views.Base.GridCell[] cells = g.GetSelectedCells();
            if (cells.Length == 0)
                return;

            double sum = 0;

            foreach (DevExpress.XtraGrid.Views.Base.GridCell gc in cells)
            {
                double val = 0.0;
                string cellVal = g.GetRowCellDisplayText(gc.RowHandle, gc.Column);
                CultureInfo ci = Application.CurrentCulture;
                double.TryParse(cellVal, NumberStyles.Any, ci, out val);

                sum += val;
            }

            adet = string.Format("{0}{1:n0}", "Adet: ", cells.Length);

            if (sum > 0)
                toplam = string.Format("{0}{1:n1}", "Toplam: ", sum);
            else
                toplam = "";

            Session.MainForm.NotifySelectionInfo(this);
        }

        public void GleExtend(params GridLookUpEdit[] gles)
        {
            List<GridLookupExtender> glex = new List<GridLookupExtender>();
            foreach (GridLookUpEdit gle in gles)
                glex.Add(new GridLookupExtender(gle));
        }

        public void AddTooltip(GridView gv, string fieldName, string tip)
        {
            gv.Columns[fieldName].ToolTip = tip;
        }

        //protected void EndGridViewEdit(GridView view)
        //{
        //    view.CloseEditor();
        //    view.UpdateCurrentRow();
        //}

        public void CenterGridColumn(GridColumn col)
        {
            col.AppearanceCell.Options.UseTextOptions = true;
            col.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
        }
        #endregion

        #region Product Photo Releated

        public byte[] ConvertImageToByteArray(Image imageToConvert, ImageFormat formatOfImage)
        {
            byte[] Ret;
            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    imageToConvert.Save(ms, formatOfImage);
                    Ret = ms.ToArray();
                }
            }
            catch (Exception) { return null; }
            return Ret;
        }

        public Image ConvertByteArrayToImage(byte[] byteArray)
        {
            try
            {
                if (byteArray != null)
                {
                    MemoryStream ms = new MemoryStream(byteArray, 0, byteArray.Length);
                    ms.Write(byteArray, 0, byteArray.Length);
                    return Image.FromStream(ms, true);
                }
            }
            catch (Exception) { return null; }
            return null;
        }

        /*
        public Image byteArrayToImage(byte[] byteArrayIn)
        {
            MemoryStream ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }
         */
        #endregion

        #region Splitter Functions

        public enum AcKapa
        {
            Expand = 0,
            Collapse
        }

        public void ExpandCollapse(SplitContainerControl sc, AcKapa action)
        {
            FieldInfo fi = typeof(SplitContainerControl).GetField("containerInfo", BindingFlags.NonPublic | BindingFlags.Instance);
            DevExpress.XtraEditors.Drawing.SplitContainerViewInfo vInfo = fi.GetValue(sc) as DevExpress.XtraEditors.Drawing.SplitContainerViewInfo;
            if ((vInfo.Splitter.IsCollapsed) ^ (action == AcKapa.Collapse))
                vInfo.Splitter.DoExpandCollapseOnClick();
        }


        #endregion

        #region Binding Source Helpers
        public void AddBsToList(params BindingSource[] bsElement)
        {
            sources = new List<BindingSource>(bsElement.Length);
            foreach (BindingSource bs in bsElement)
                sources.Add(bs);
        }

        public void EndEdits()
        {
            this.Validate();
            if (sources != null)
                foreach (BindingSource bs in sources)
                    bs.EndEdit();
        }
        #endregion

        #region Check Functions
        public bool checkEmpty(GridView View, string cols)
        {
            bool found = false;
            //View.BeginSort();
            try
            {
                // Traverse data rows and change the Price field values.
                for (int i = 0; i < View.DataRowCount && !found; i++)
                    foreach (string col in cols.Split(';'))
                        if (View.GetRowCellValue(i, col) == DBNull.Value)
                        {
                            found = true;
                            break;
                        }
            }
            finally
            {
                //View.EndSort();
            }
            return found;
        }

        public bool checkEmpty(DataTable dt, string cols)
        {
            bool found = false;
            //View.BeginSort();
            try
            {
                // Traverse data rows and change the Price field values.
                for (int i = 0; i < dt.Rows.Count && !found; i++)
                    foreach (string col in cols.Split(';'))
                        if (dt.Rows[i][col] == DBNull.Value)
                        {
                            found = true;
                            break;
                        }
            }
            finally
            {
                //View.EndSort();
            }
            return found;
        }
        #endregion

        #region Tab Page Helpers
        List<XtraTabControl> tabs = new List<XtraTabControl>();
        Dictionary<XtraTabPage, string[]> tabPageInfos = new Dictionary<XtraTabPage, string[]>();

        public void SetTabPageInfo(string Header, string Status, XtraTabPage tp)
        {
            if (!tabs.Contains(tp.TabControl))
            {
                tp.TabControl.SelectedPageChanged += TabControl_SelectedPageChanged;
                tabs.Add(tp.TabControl);
            }

            if (!tabPageInfos.ContainsKey(tp))
            {
                tabPageInfos.Add(tp, new string[2] { Header, Status });
            }
            else
            {
                tabPageInfos[tp].SetValue(Header, 0);
                tabPageInfos[tp].SetValue(Status, 1);
            }
        }

        void TabControl_SelectedPageChanged(object sender, TabPageChangedEventArgs e)
        {
            if (tabPageInfos.ContainsKey(e.Page))
            {
                string[] vals = tabPageInfos[e.Page];
                txtInfo.Caption = vals[0];
                //   NotifySelectionInfo(vals[1]);
            }
        }

        public void SelectTabPage(XtraTabControl tab, XtraTabPage tp)
        {
            tab.SelectedTabPage = tp;
            foreach (XtraTabPage x in tab.TabPages)
                x.PageVisible = (x == tp);
        }
        #endregion

        #region Memory Stream Helpers
        public string MemoryStreamToString(MemoryStream ms)
        {
            ms.Seek(0, SeekOrigin.Begin);
            byte[] bytes = new byte[ms.Length];
            ms.Read(bytes, 0, (int)ms.Length);
            return System.Text.Encoding.GetEncoding("ISO-8859-9").GetString(bytes);
        }

        public MemoryStream StringToMemoryStream(string str)
        {
            byte[] a = System.Text.Encoding.GetEncoding("ISO-8859-9").GetBytes(str);
            return new System.IO.MemoryStream(a);
        }
        #endregion

        #region Summary Functions
        public void AddAverage(GridView gv, params string[] flds)
        {
            gv.OptionsView.ShowFooter = true;
            foreach (string fld in flds)
            {
                gv.Columns[fld].SummaryItem.FieldName = fld;
                gv.Columns[fld].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Average;
                gv.Columns[fld].SummaryItem.DisplayFormat = "AVG: {0:#,##0.##}";
            }
        }

        public void AddGroupSummary(GridView gv, params string[] flds)
        {
            gv.OptionsView.GroupFooterShowMode = GroupFooterShowMode.VisibleAlways;
            foreach (string fld in flds)
            {
                GridGroupSummaryItem item1 = new GridGroupSummaryItem();

                if (fld == "TotalRecords")
                {
                    foreach (GridColumn col in gv.Columns)
                        if (col.Visible == true)
                        {
                            item1.FieldName = col.FieldName;
                            item1.SummaryType = DevExpress.Data.SummaryItemType.Count;
                            item1.DisplayFormat = "{0:#,##0} records";
                            break;
                        }
                }
                else
                {
                    item1.FieldName = fld;
                    item1.SummaryType = DevExpress.Data.SummaryItemType.Sum;
                    item1.DisplayFormat = "{0:#,##0.00}";
                }
                item1.ShowInGroupColumnFooter = gv.Columns[fld];
                gv.GroupSummary.Add(item1);
            }
        }
        #endregion

        #region Text Formatting
        public void _FormatAsNumeric(DevExpress.XtraGrid.Columns.GridColumn col)
        {
            //else if (col.FieldName.Contains("Qty") || col.FieldName == "AyrimMt" || col.FieldName == "Alt" || col.FieldName == "Ust")
            //{
            //    col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
            //    col.DisplayFormat.Format = new FormatMetre();
            //}

            col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            col.DisplayFormat.FormatString = "#,###";
            col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;
        }

        public void _FormatAsNumeric2(DevExpress.XtraGrid.Columns.GridColumn col)
        {
            col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            col.DisplayFormat.FormatString = "#,##0.00";
            col.FilterMode = DevExpress.XtraGrid.ColumnFilterMode.Value;
        }
        #endregion

        #region Parse Functions
        public decimal decimalParse(BindingSource bs, string ColumnName)
        {
            decimal tmp = 0;
            if (bs.Current != null)
                decimal.TryParse(((DataRowView)bs.Current).Row[ColumnName].ToString(), out tmp);
            return tmp;
        }

        public int intParse(BindingSource bs, string ColumnName)
        {
            int tmp = 0;
            if (bs != null)
                if (bs.Current != null)
                    int.TryParse(((DataRowView)bs.Current).Row[ColumnName].ToString(), out tmp);
            return tmp;
        }

        public string strParse(BindingSource bs, string ColumnName)
        {
            string tmp = string.Empty;
            if (bs != null)
                if (bs.Current != null)
                    tmp = ((DataRowView)bs.Current).Row[ColumnName].ToString();
            return tmp;
        }

        public bool boolParse(object str)
        {
            if (str == null)
                return false;
            else
            {
                bool tmp = false;
                bool.TryParse(str.ToString(), out tmp);
                return tmp;
            }
        }

        public int intParse(object str)
        {
            if (str == null)
                return 0;
            else
            {
                int tmp = 0;
                int.TryParse(str.ToString(), out tmp);
                return tmp;
            }
        }

        public string strParse(object str)
        {
            if (str == null)
                return string.Empty;
            else
                return str.ToString();
        }

        public decimal decimalParse(object str)
        {
            if (str == null)
                return 0;
            else
            {
                decimal tmp = 0;
                decimal.TryParse(str.ToString(), out tmp);
                return tmp;
            }
        }

        public DateTime datetimeParse(object str)
        {
            DateTime tmp = new DateTime(2000, 1, 1);  //DateTime.MinValue;
            if (str != null)
                if (str != DBNull.Value)
                    DateTime.TryParse(str.ToString(), out tmp);

            return tmp;
        }

        #endregion

        #region Database Helpers
        public void ExecuteNonQuery(string SP, params object[] prm)
        {
            bool changeCursor = this.Cursor == Cursors.Default;
            try
            {
                if (changeCursor)
                    this.Cursor = Cursors.WaitCursor;
                Session.DataManager.ExecuteNonQuery(SP, prm);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                if (changeCursor)
                    this.Cursor = Cursors.Default;
            }
        }

        public DataTable ExecuteDataTable(string SP, params object[] prm)
        {
            bool changeCursor = this.Cursor == Cursors.Default;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                return Session.DataManager.ExecuteDataTable(SP, prm);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {

                if (changeCursor)
                    this.Cursor = Cursors.Default;
            }
        }

        public DataTable ExecuteDataTableByQuery(string Query)
        {
            bool changeCursor = this.Cursor == Cursors.Default;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                return Session.DataManager.ExecuteDataTableByQuery(Query);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {

                if (changeCursor)
                    this.Cursor = Cursors.Default;
            }
        }


        public void RunSP(ExecuteTypes executeType, Action<DataManager.SP> CompletedMethod1, string nameOrQuery, params object[] parameters)
        {
            foreach (Control c in this.Controls)
            {
                c.Tag = c.Enabled;
                c.Enabled = false;
            }

            DataManager.SP sp = Session.DataManager.RunSP(executeType, CompletedMethod1, sp_Completed, nameOrQuery, parameters);
        }

        void sp_Completed(DataManager.SP sp)
        {
            foreach (Control c in this.Controls)
                c.Enabled = (bool)c.Tag;
        }


        public DataSet ExecuteDataSet(string SP, params object[] prm)
        {
            bool changeCursor = this.Cursor == Cursors.Default;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                return Session.DataManager.ExecuteDataSet(SP, prm);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                if (changeCursor)
                    this.Cursor = Cursors.Default;
            }
        }

        public object ExecuteScalar(string SP, params object[] prm)
        {
            bool changeCursor = this.Cursor == Cursors.Default;
            try
            {
                this.Cursor = Cursors.WaitCursor;
                return Session.DataManager.ExecuteScalar(SP, prm);
            }
            catch (Exception Ex)
            {
                throw (Ex);
            }
            finally
            {
                if (changeCursor)
                    this.Cursor = Cursors.Default;
            }
        }
        #endregion

        #region Message Dialogs
        protected DialogResult ShowErrorMessage(string message)
        {
            return XtraMessageBox.Show(message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        protected DialogResult ShowInfoMessage(string message)
        {
            return XtraMessageBox.Show(message, "Bilgi", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        protected static void ShowMessage(string message)
        {
            XtraMessageBox.Show(message);
        }

        protected static void ShowMessage(Exception exception)
        {
            XtraMessageBox.Show(exception.ToString(), "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        #endregion

        #region ValidationProvider
        public struct InvalidControl
        {
            public LabelControl Label;
            public string ErrorText;
            public Control Control;
            public Color BackColor;
            public Color ForeColor;
            public InvalidControl(LabelControl label, string errorText, Control control)
            {
                this.Control = control;
                this.ErrorText = errorText;
                this.Label = label;
                this.BackColor = control.BackColor;
                this.ForeColor = label.ForeColor;
            }
        }
        public Dictionary<Control, InvalidControl> InvalidControls = new Dictionary<Control, InvalidControl>();

        public bool ValidateAll(bool blink = true)
        {
            foreach (KeyValuePair<Control, InvalidControl> invalids in InvalidControls)
            {
                InvalidControl ictrl = invalids.Value;
                ictrl.Label.Font = new System.Drawing.Font(ictrl.Label.Font, System.Drawing.FontStyle.Regular);
                ictrl.Control.BackColor = ictrl.BackColor;
                ictrl.Label.ForeColor = ictrl.ForeColor;
                ictrl.Label.ToolTip = "";
                ictrl.Label.Cursor = Cursors.Default;
            }

            bool validatorOK = ValidationProvider.Validate();
            if (validatorOK)
                return true;
            else
            {
                foreach (Control ctrl in ValidationProvider.GetInvalidControls())
                {
                    InvalidControl ictrl = InvalidControls[ctrl];

                    if (blink)
                        ictrl.Control.BackColor = System.Drawing.Color.Red;

                    ictrl.Label.ToolTip = ictrl.ErrorText;
                    ictrl.Label.Font = new System.Drawing.Font(ictrl.Label.Font, FontStyle.Underline);
                    ictrl.Label.ForeColor = Color.Black;
                    ictrl.Label.Cursor = Cursors.Help;
                }
                if (blink && !Session.isProblematicUser)
                    ValidatorTimer.Start();
                return false;
            }
        }

        public class NullValidationRule : ValidationRule
        {
            public override bool Validate(Control control, object value)
            {
                bool returnValue = false;
                string controlType = control.GetType().Name;

                switch (controlType)
                {
                    case "LookUpEdit":
                        if (((LookUpEdit)control).EditValue != null)
                        {
                            returnValue = true;
                        }
                        break;
                    case "GridLookUpEdit":
                        if (((GridLookUpEdit)control).EditValue != null)
                        {
                            returnValue = true;
                        }
                        break;
                    case "DateEdit":
                        if (((DateEdit)control).EditValue != null)
                        {
                            returnValue = true;
                        }
                        break;
                }

                return returnValue;
            }
        }
        void ValidatorTimer_Tick(object sender, EventArgs e)
        {
            foreach (Control ctrl in ValidationProvider.GetInvalidControls())
            {
                InvalidControl ictrl = InvalidControls[ctrl];
                ictrl.Control.BackColor = ictrl.BackColor;
            }

            ValidatorTimer.Stop();
        }

        Timer ValidatorTimer;
        public ConditionValidationRule cvrEmpty;
        protected NullValidationRule cvrNull;
        public void InitValidation()
        {
            if (this.DesignMode)
                return;

            if (!Session.isProblematicUser)
            {
                ValidatorTimer = new Timer();
                cvrEmpty = new ConditionValidationRule();
                cvrEmpty.ConditionOperator = ConditionOperator.IsNotBlank;
                cvrEmpty.ErrorText = "Lütfen bir değer giriniz.";

                cvrNull = new NullValidationRule();
                cvrNull.ErrorText = "Lütfen bir değer seçiniz.";

                ValidationProvider.ValidationMode = ValidationMode.Manual;
                ValidatorTimer.Tick += ValidatorTimer_Tick;
                ValidatorTimer.Interval = 200; // in miliseconds
            }
        }
        #endregion

        #region Statusbar Notifications
        public static void Notify(string str)
        {
            Session.MainForm.NotifyMain(str);
        }

        string selectionInfo = "";
        public string SelectionInfo
        {
            get
            {

                string seperator = "  " + ((char)183) + "  ";
                List<string> result = new List<string>();

                result.Add(adet);

                if (toplam != "")
                    result.Add(toplam);

                if (selectionInfo != "")
                    result.Add(selectionInfo);

                return string.Join(seperator, result.ToArray());
            }
            set
            {
                selectionInfo = value;
                Session.MainForm.NotifySelectionInfo(this);
            }
        }
        #endregion

        /* Birbirine bağlı verilerde hiyerarşik filtreleme TODO:
        //http://documentation.devexpress.com/#WindowsForms/DevExpressXtraGridViewsBaseColumnView_ShownEditortopic
        //bunu GLE de de kullanabilmek için gridden bağımsız (gle eventleriyle) çalıştırabilir miyiz?

        private DataView clone = null;

        void GridView_ShownEditor(object sender, EventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view;
            {
                view = sender as DevExpress.XtraGrid.Views.Grid.GridView;
                if (view.ActiveEditor is DevExpress.XtraEditors.GridLookUpEdit)
                {
                    GridLookUpEdit edit = (GridLookUpEdit)view.ActiveEditor;
                    DataTable table = edit.Properties.DataSource as DataTable;

                    //if (table.Columns.Contains("Deleted"))
                    if (table.TableName == "Brand" || table.TableName == "V_Customer")
                    {
                        clone = new DataView(table);

                        if (clone != null)
                            clone.RowFilter = "isNull(Deleted, 0) = 0";

                        edit.Properties.DataSource = clone;
                    }
                }
            }
        }         

        void GridView_HiddenEditor(object sender, EventArgs e)
        {
            if (clone != null)
                clone.RowFilter = "";
        }
        */

        public string Hash { get; set; }
    }
}
